package com.cby.android.olive.ext

import com.cby.android.olive.encrypt.Md5Utils
import java.lang.Exception
import java.net.URLEncoder
import java.nio.charset.Charset

/**
 * @description: StringExt
 * @author: ChenBaoYang
 * @createDate: 2022/12/5 11:22 上午
 */

/**
 * 字符串- URLEncoder
 */
fun String.encodeUTF8() : String {
    return URLEncoder.encode(this,"utf-8")
}

/**
 * md5加密
 */
fun String.md5(): String {
    return Md5Utils.md5(this)
}

/**
 * 字符串转换为16进制字符串
 *
 * @param s
 * @return
 */
fun String.hex(): String {
    var str = ""
    for (element in this) {
        val ch = element.toInt()
        val s4 = Integer.toHexString(ch)
        str += s4
    }
    return str
}

fun String.hexToString() : String {
    var s = this.replace(" ", "")
    val baKeyword = ByteArray(s.length / 2)
    for (i in baKeyword.indices) {
        try {
            baKeyword[i] = (0xff and
                    s.substring(i * 2, i * 2 + 2).toInt(16)).toByte()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    try {
        s = String(baKeyword, Charset.forName("gbk"))
        String()
    } catch (e1: Exception) {
        e1.printStackTrace()
    }
    return s
}

/**
 * 16进制表示的字符串转换为字节数组
 *
 * @param s 16进制表示的字符串
 * @return byte[] 字节数组
 */
fun hexStringToByteArray(s: String): ByteArray {
    val len = s.length
    val b = ByteArray(len / 2)
    var i = 0
    while (i < len) {
        // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
        b[i / 2] = ((Character.digit(s[i], 16) shl 4) + Character
            .digit(s[i + 1], 16)).toByte()
        i += 2
    }
    return b
}

/**
 * byte数组转16进制字符串
 * @param bArray
 * @return
 */
fun bytesToHexString(bArray: ByteArray): String {
    val sb = StringBuffer(bArray.size)
    var sTemp: String
    for (i in bArray.indices) {
        sTemp = Integer.toHexString(0xFF and bArray[i].toInt())
        if (sTemp.length < 2) sb.append(0)
        sb.append(sTemp.toUpperCase())
    }
    return sb.toString()
}





